package servlet;

import domain.Product;
import util.JDBCUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "/MenuSearchServlet", value = "/MenuSearchServlet")
public class MenuSearchServlet extends HttpServlet {


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object username = request.getSession().getAttribute("username");
        if (username == null) return;
        String name = request.getParameter("text");
        if (Objects.isNull(name)) name = "";
        Connection connection = JDBCUtil.getConnection();
        int page = 0;
        int pageSize = 3;
        if (request.getParameter("page") != null && request.getParameter("page") != "") {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (request.getParameter("pageSize") != null && request.getParameter("pageSize") != "") {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        String sql = "SELECT * FROM products where name like '%" + name + "%' limit " + page * pageSize + ", " + pageSize;
        Statement statement = null;
        List<Product> productList = new ArrayList<Product>();

        try {
            statement = connection.createStatement();
            ResultSet res = statement.executeQuery(sql);

            while (res.next()) {
                Product product = new Product();
                product.setId(res.getString(1));
                product.setName(res.getString(2));
                product.setPrice(res.getDouble(3));
                product.setCategory(res.getString(4));
                product.setPnum(res.getInt(5));
                product.setImgurl(res.getString(6));
                product.setDescription(res.getString(7));
                productList.add(product);
            }

            request.setAttribute("ProductList", productList);
            request.getRequestDispatcher("/client/ProductList.jsp").forward(request, response);
//            response.sendRedirect("/BookStore/client/ProductList.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
